<script setup lang="ts">
import type RadioOption from './RadioOption.ts'

const props = defineProps({
  label: String,
  modelValue: [String, Number],
  options: {
    type: Array as () => RadioOption[],
    default: () => []
  },
  disabled: Boolean,
  vertical: Boolean
})

const emit = defineEmits(['update:modelValue', 'change'])

function isDisabled(option: RadioOption) {
  return props.disabled || option.disabled
}

function select(option: RadioOption) {
  if (isDisabled(option)) return
  if (option.value !== props.modelValue) {
    emit('update:modelValue', option.value)
    emit('change', option.value)
  }
}
</script>

<template>
  <div class="radio-group" :class="{vertical}">
    <span class="radio-group-label">{{ label }}</span>
    <div
        v-for="option in options"
        :key="option.value"
        class="radio-item"
        :class="{ checked: option.value === modelValue, disabled: isDisabled(option) }"
        @click="select(option)">
      <span class="radio-circle">
        <span v-if="option.value === modelValue" class="radio-dot"/>
      </span>
      <span class="radio-label">{{ option.label }}</span>
    </div>
  </div>
</template>

<style scoped>
.radio-group {
  display: flex;
  flex-direction: row;
  padding: 10px;
  gap: 8px;
}

.radio-group.vertical {
  flex-direction: column;
}

.radio-group-label {
  font-weight: bold;
}

.radio-item {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.radio-item.disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.radio-circle {
  width: 16px;
  height: 16px;
  border: 1px solid #999;
  border-radius: 50%;
  margin-right: 8px;

  display: flex; /* 添加这行 */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
}

.radio-dot {
  width: 8px;
  height: 8px;
  background-color: #409EFF;
  border-radius: 50%;
}

.radio-label {
  user-select: none;
}

.radio-item.checked .radio-circle {
  border-color: #409EFF;
}
</style>
